package com.example.smoke;

import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.net.Uri;
import android.net.vcn.VcnCellUnderlyingNetworkTemplate;
import android.media.Image;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.Instant;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import java.io.IOException;
import android.Manifest;
import pub.devrel.easypermissions.EasyPermissions;




public class FunctionActivity extends AppCompatActivity {

    //声明控件
    private ImageView mIvHead;
    private com.example.smoke.SlideMenu slidedMenu;
    private Button mBtnMain1;
    private Button mBtnMain2;
    private Button mBtnMain3;
    private Button mBtnMain4;

    public static Uri imageUri;

    ActivityResultLauncher<Intent> cameraLauncher;
    ActivityResultLauncher<Intent> albumLauncher;

    int CAMERA_REQUEST_CODE=433;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_function);

        //找到控件
        mIvHead = findViewById(R.id.iv_head);
        slidedMenu = findViewById(R.id.slideMenu);
        mBtnMain1 = findViewById(R.id.btn_main_1);  //产品介绍
        mBtnMain2 = findViewById(R.id.btn_main_2);  //选图片
        mBtnMain3 = findViewById(R.id.btn_main_3);  //拍图片
        mBtnMain4 = findViewById(R.id.btn_main_4);  //返回上一级

        if(!(EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA))){
            EasyPermissions.requestPermissions(
                    this,
                    "需要相机权限",
                    CAMERA_REQUEST_CODE,
                    Manifest.permission.CAMERA);
        }
        //相册和相机的回调函数
        albumLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK
                            && result.getData() != null) {
                        imageUri = result.getData().getData();
                        //出现并解决了很诡异的bug
                        //原先相机可以正常裁剪但是相册无法裁剪，ucrop库直接报错
                        //解决方法是相册模拟了相机裁剪前发生的行为，uri指向app内部路径重建的图片
                        //以下到调用ucrop库前全部是模拟行为
                        Bitmap bitmap;
                        try {
                            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        File outputImage = new File(getExternalCacheDir(), "smoke.jpg");
                        if (outputImage.exists()) {
                            outputImage.delete();
                        }
                        try {
                            outputImage.createNewFile();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        FileOutputStream outputStream;
                        try {
                            outputStream = new FileOutputStream(outputImage);
                        } catch (FileNotFoundException e) {
                            throw new RuntimeException(e);
                        }

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            imageUri = FileProvider.getUriForFile(FunctionActivity.this, "com.example.smoke.fileprovider", outputImage);
                        } else {
                            imageUri = Uri.fromFile(outputImage);
                        }
                        UCrop.of(imageUri, imageUri).start(FunctionActivity.this);
                    }
                }
        );
        cameraLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        UCrop.of(imageUri, imageUri).start(FunctionActivity.this);
                    }
                }
        );

        mBtnMain2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                albumLauncher.launch(intent);
            }
        });
        mBtnMain3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File outputImage = new File(getExternalCacheDir(), "smoke.jpg");
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                try {
                    outputImage.createNewFile();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(FunctionActivity.this, "com.example.smoke.fileprovider", outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                cameraLauncher.launch(intent);
            }
        });


        //实现侧滑，点击加侧滑
        mIvHead.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                slidedMenu.switchMenu();
            }
        });

        setListener();

    }
    //ucrop的回调
    //我来不及理解要怎么用新的回调写法写外部库的回调了，凑合用旧的
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            Intent intent=new Intent();
            intent.setClass(FunctionActivity.this,ResultActivity.class);
            startActivity(intent);
        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
        }
    }

    private void setListener(){
        OnClick onClick = new OnClick();

        //对1 4按钮进行setonclicklistener
        mBtnMain1.setOnClickListener(onClick);
        mBtnMain4.setOnClickListener(onClick);


    }

    private class OnClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Intent intent= null;
            int id = v.getId();
            if (id == R.id.btn_main_1) {
                intent = new Intent(FunctionActivity.this, introductionActivity.class);
            }else if (id == R.id.btn_main_4) {
                intent = new Intent(FunctionActivity.this, MainActivity.class);
            }
            startActivity(intent);
        }
    }
}